package com.app.controller;

import com.app.model.AdminUserModel;
import com.app.model.PermissionModel;
import com.app.model.RoleModel;
import com.app.service.AdminUserService;
import com.app.service.PermissionService;
import com.app.service.RoleService;
import com.app.util.Result;
import com.app.util.SpringUtils;
import com.app.util.TokenUtils;
import io.netty.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class BaseController {

    @Resource
    private AdminUserService adminUserService = SpringUtils.getBean(AdminUserService.class);

    @Resource
    private RoleService roleService = SpringUtils.getBean(RoleService.class);
    @Resource
    private PermissionService permissionService = SpringUtils.getBean(PermissionService.class);

    /**
     * 验证是否登录
     *
     * @param request
     * @return
     */
    public boolean verifyPermissions(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return false;
        }
        String userId = TokenUtils.verify(token);
        if (userId == null) {
            return false;
        } else {
            AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
            if (user == null) {
                return false;
            }
            return true;
        }
    }

    /**
     * 判断是否有权限
     *
     * @param request
     * @return
     */
    public boolean competence(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return false;
        }
        String userId = TokenUtils.verify(token);
        //获取当前登录对象的全部信息
        AdminUserModel adminUserModel = adminUserService.getUserByUserId(Integer.parseInt(userId));
        //管理员拥有全部权限
//        if (Integer.parseInt(userId) == 1) {
//            return true;
//        }
        //从请求头中获取的地址
        String requestURI = request.getRequestURI();
        //通过角色id查询当前登陆对象的所有权限
        //根据URL查询权限
        PermissionModel permissionModel = permissionService.getRoleByUrl(requestURI);
        if (permissionModel == null) {//如果与表内比对没有权限就返回false
            return false;
        }
        RoleModel roleModel = roleService.getRoleByRoleId(adminUserModel.getRoles());
        String[] roleArr = roleModel.getRules().split(";");//获取权限字符串
        for (String s : roleArr) {
            if (permissionModel.getPerms().equals(s)) {
                return true;
            }

        }
        return false;
    }

}
